package com.diy.sigmund.diygateway.controller;

import com.diy.sigmund.diycommon.entity.ResultMsg;
import com.diy.sigmund.diycommon.entity.constant.LogConstant;
import com.diy.sigmund.diycommon.entity.enumerate.ResponseEnum;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * http://c.biancheng.net/view/5417.html
 * 错误页面返回固定好的 Json 格式的数据
 *
 * @author ylm-sigmund
 * @since 2021/9/3 14:35
 */
@RestController
public class ErrorHandlerController implements ErrorController {

    @Autowired
    private ErrorAttributes errorAttributes;
    private static final Logger log = LoggerFactory.getLogger(ErrorHandlerController.class);

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    public ResultMsg error(HttpServletRequest request) {
        Map<String, Object> errorAttributes = getErrorAttributes(request);
        String data = (String) errorAttributes.get("message");
        String trace = (String) errorAttributes.get("trace");
        if (StringUtils.isNotBlank(trace)) {
            data += String.format("and trace %s", trace);
        }
        log.info(LogConstant.SPRING_LOG, "网关异常处理1进入全局异常处理器");
        return ResultMsg.fail(ResponseEnum.GATEWAY_FAIL, data);
    }

    private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
        return errorAttributes.getErrorAttributes(new ServletWebRequest(request), true);
    }
}
